<template>
    <edu-dialog ref="photoDialog" :title="title" size="small" @confirm="savePhoto">
        <el-upload
            :headers="{'X-Token': $store.state.session.sessionid}"
            class="avatar-uploader"
            action="/api/commonservice/obsfile/uploadfile"
            :data="{bucketname: 'face', folderpath: 'file'}"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
        >
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
    </edu-dialog>
</template>
<script>
export default {
    name: "picUploadDialog",
    props: ["title"],
    data() {
        return {
            imageUrl: "",
            objectKey: ""
        };
    },
    methods: {
        open() {
            this.imageUrl = "";
            this.objectKey = "";
            this.$refs.photoDialog.open();
        },
        close() {
            this.$refs.photoDialog.close();
        },
        savePhoto() {
            if (this.objectKey) {
                this.$emit("success", this.objectKey);
                this.close();
            } else {
                this.$message.error("请选择需要上传的照片!");
            }
        },
        handleAvatarSuccess(res, file) {
            this.imageUrl = URL.createObjectURL(file.raw);
            this.objectKey = res.data[file.name].objectkey;
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === "image/jpeg";
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error("上传头像图片只能是 JPG 格式!");
            }
            if (!isLt2M) {
                this.$message.error("上传头像图片大小不能超过 2MB!");
            }
            return isJPG && isLt2M;
        }
    }
};
</script>
<style lang="scss" scoped>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}
.avatar-uploader-icon {
    border: 1px dashed #d9d9d9;
    font-size: 28px;
    color: #8c939d;
    width: 110px;
    height: 140px;
    line-height: 140px;
    text-align: center;
}
.avatar {
    width: 110px;
    height: 140px;
    display: block;
}
</style>